/************************************************************************
*************************************************************************
*************************************************************************

ajayrd.ado

Creates RD graph with estimated discontinuity and standard error. Assumes
cutoff is zero.

20180227:	(@) Created


varlist: 		[outcome] [running variable]
bw:				bandwidth
deg:			degree of polynomial (default is linear)
controlvars:	Controls
clusterlist:	variables that form the clusters (for standard errors)
binsize:		width of "dots"
dplabel:		Label for right of cutoff (default: no label)
dnlabel:		Label for left of cutoff (default: no label)
dppos:			Optional override for position of dplabel
dnpos:			Optional override for position of dnlabel
discpos:		Optional override for position of word "Discontinuity:"
estpos:			Optional override for position of estimate (SE appears below it)

Scatter options:
title,xtitle,ytitle,ylabel,xlabel,name,yline

Example:

#d;
ajayrd zndays rv, bw(.05) xtitle("Vote Margin", size(vlarge)) ytitle("Days of Labor", size(vlarge))
		name(g`year') title("`lab`year''", size(huge) )
		discpos(60 -.03) estpos(60 -.01) xlabel(-.05(.025).05)
		ylabel(10(20)70)
		;
#d cr

*************************************************************************
*************************************************************************
************************************************************************/



	

cap program drop ajayrd
program ajayrd
	#delimit;
	syntax varlist(max=2 min=2 ts fv),  bw(real) 
			[deg(integer 1) CONtrolvars(varlist) CLUSTerlist(varlist) NOOFFset
			
			BINsize(real 0) DPLabel(string asis) DNLabel(string asis) 
			DPPos(numlist min=2 max=2) DNPos(numlist min=2 max=2)
			DISCPos(numlist min=2 max=2) ESTPos(numlist min=2 max=2)
			
			xtitle(passthru) ytitle(passthru) ylabel(passthru) xlabel(passthru)
			title(passthru) name(passthru) yline(passthru) ]
	;
	#delimit cr
	

	tempfile pre
	save `pre'
	
	//Outcome
	local out : word 1 of `varlist'
	local run : word 2 of `varlist'
	
	//Bin size (if needed)
	if `binsize' == 0 {
		local binsize = `bw' / 10
	}

	//Cluster (for standard errors)
	tempvar clust
	if !mi("`clusterlist'") {
		egen `clust' 	= group(`clusterlist')
	}
	else {
		gen `clust' 	= _n
	}
	

	//Indicator for control of the assembly
	gen control = (`run' >= 0) if !mi(`run')

	//Restrict to bandwidth
	keep if abs(`run') < `bw'

	//Generate control function
	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}


	//Run regression on micro data
	reg `out' poly* control c.control#c.poly* `controlvars', cluster(`clust')

	//Size of discontinuity and standard error
	local b 	= string( _b[control], "%9.3f" )
	local se 	= string( _se[control], "%9.3f" )

	//Round to construct bins
	gen bin = `run' - mod(`run',`binsize')

	//Take bin averages (and counts)
	gen nonmi = e(sample)
	collapse `out' (sum)nobs=nonmi, by(bin)

	//Recenter the running variable on the midpoints of the bins
	if mi("`nooffset'") {
		gen `run' 					= bin+`binsize'/2
	}
	else {
		gen `run' 					= bin
	}
	gen control					= `run' > 0


	forvalues p=1/`deg' {
		gen poly`p' = `run'^`p'
	}
	predict pred
	
	if mi("`dppos'") | mi("`dnpos'") {
		sum `out'
		local bottom = r(min) + ( r(max)-r(min) )*.025
		
		sum `run'
		local left 	= r(min) + ( r(max)-r(min) )*.05
		local right = ( r(max)-r(min) )*.05
		
		local dnpos `bottom' `left'
		local dppos `bottom' `right'
	}

	if mi("`discpos'") | mi("`estpos'") {
		sum `out'
		local top = r(max) - ( r(max)-r(min) )*.15
		
		sum `run'
		local word 	= r(min) + ( r(max)-r(min) )*.15
		local est 	= `word' + ( r(max)-r(min) )*.18
		
		local discpos `top' `word'
		local estpos `top' `est'
	}
	


	#delimit;
	twoway 
	(scatteri 	`dnpos' `dnlabel'
					`dppos' `dplabel', ms(i) mlabsize(large) mlabcolor(gs10) )
	(scatter `out' `run' , msize(2) mc(navy) )				//Dots
	(line pred `run' if control)  				//Fit: Republican control
	(line pred `run' if !control) 				//Fit: Democratic control
	,
	text(`discpos' "Discontinuity:", size(medlarge) )  text(`estpos' "`b'" "(`se')", size(medlarge) ) 
	graphregion(color(white)) legend(off) xline(0, lc(gs14) lp(dash) ) 
	`xtitle' `ytitle' `ylabel' `xlabel' `name' `yline' `title'
	;
	#delimit cr
	
	use `pre', clear

end
